package com.demo.servlet.demo1221.demo02.listener;

import com.demo.servlet.demo1221.demo02.entity.User;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.util.LinkedHashMap;
import java.util.Map;

//@WebListener
public class UserListener implements HttpSessionAttributeListener {
    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        //获取添加到Session的name是否为 user
        if (event.getName().equals("user")) {
            //获取在线名单
            Map<String, User> onlineUsers = (Map<String, User>) event.getSession().getServletContext().getAttribute("onlineUsers");
            //对在线名单是否存在 进行判断
            if (onlineUsers == null) {
                onlineUsers = new LinkedHashMap<String, User>();
            }
            //获取到本次添加到session中的user对象
            User user = (User) event.getValue();
            //把用户保存到在线名单中
            onlineUsers.put(user.getUsername(), user);
            //把在线名单 放回ServletContext
            event.getSession().getServletContext().setAttribute("onlineUsers", onlineUsers);
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        //当用户被移除出session时
        if (event.getName().equals("user")) {
            User oldUser = (User) event.getValue();
            //获取在线名单
            Map<String, User> onlineUsers = (Map<String, User>) event.getSession().getServletContext().getAttribute("onlineUsers");
            //从在线名单中移除 User
            if (onlineUsers != null) {
                onlineUsers.remove(oldUser.getUsername());
            }
        }
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        //当用户另外登录一个账号的时候
        if (event.getName().equals("user")) {
            //获取在线名单
            Map<String, User> onlineUsers = (Map<String, User>) event.getSession().getServletContext().getAttribute("onlineUsers");
            //对在线名单是否存在 进行判断
            if (onlineUsers == null) {
                onlineUsers = new LinkedHashMap<String, User>();
            }
            //拿到被替换的 User 老User
            User oldUser = (User) event.getValue();
            //移除老 User
            onlineUsers.remove(oldUser.getUsername());
            //获取新User
            User newUser = (User) event.getSession().getAttribute("user");
            //把用户保存到在线名单中
            onlineUsers.put(newUser.getUsername(), newUser);
            //把在线名单 放回ServletContext
            event.getSession().getServletContext().setAttribute("onlineUsers", onlineUsers);
        }
    }
}
